package com.lzb.musicplayer.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

/**
 * 耳机插拔广播接收器
 */
public class HeadsetReceiver extends BroadcastReceiver {
    
    private OnHeadsetStateChangedListener listener;
    
    public interface OnHeadsetStateChangedListener {
        /**
         * 耳机已连接
         */
        void onHeadsetConnected();
        
        /**
         * 耳机已断开
         */
        void onHeadsetDisconnected();
    }
    
    public void setOnHeadsetStateChangedListener(OnHeadsetStateChangedListener listener) {
        this.listener = listener;
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
            int state = intent.getIntExtra("state", -1);
            if (state == 1) {
                // 耳机插入
                if (listener != null) {
                    listener.onHeadsetConnected();
                }
            } else if (state == 0) {
                // 耳机拔出
                if (listener != null) {
                    listener.onHeadsetDisconnected();
                }
            }
        }
    }
    
    /**
     * 注册广播接收器
     * @param context 上下文
     */
    public void register(Context context) {
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        context.registerReceiver(this, filter);
    }
    
    /**
     * 注销广播接收器
     * @param context 上下文
     */
    public void unregister(Context context) {
        try {
            context.unregisterReceiver(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}